package org.dromara.business.sensitive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SensitiveWordFilter {

    private SensitiveFilter sensitiveFilter;

    // 加载敏感词文件
    @PostConstruct
    public void loadSensitiveWords() throws IOException {
        // 从 resources 下加载文件
        List<String> sensitiveWords = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("sensitive_words_lines.txt"))))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sensitiveWords.add(line.trim());
            }
        }
        sensitiveFilter = new SensitiveFilter(sensitiveWords);
        log.info("敏感词加载完成");
    }

    // 过滤敏感词并输出日志
    public String filterContent(String content) {
        log.info("开始过滤内容: {}", content);

        // 获取命中的敏感词
        Set<String> matchedWords = sensitiveFilter.getMatchedWords(content);
        if (!matchedWords.isEmpty()) {
            log.info("命中敏感词: {}", matchedWords);
        }

        // 替换敏感词并输出日志
        String filteredContent = sensitiveFilter.replace(content, '*');
        log.info("过滤后的内容: {}", filteredContent);

        return filteredContent;
    }
}
